package com.weetop.akly.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.PermissionChecker;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.TimeUtils;
import com.weetop.akly.R;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cc.shinichi.library.ImagePreview;
import cc.shinichi.library.view.listener.OnBigImagePageChangeListener;
import cc.shinichi.library.view.listener.OnOriginProgressListener;

/**
 * Created by yzhya on 2017/aa/20.
 */

public class BaseUtils {

    public static final int DELAY = 365;

    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        imm.showSoftInput(editText, 0);
    }

    public static boolean checkApkExist(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    public static void toActivity(Activity activity, Class<?> clz) {
        Intent intent = new Intent();
        intent.setClass(activity, clz);
        activity.startActivity(intent);
    }

    public static void toActivity(Activity activity, Class<?> clz, String id) {
        Intent intent = new Intent();
        intent.setClass(activity, clz);
        intent.putExtra("id", id);
        activity.startActivity(intent);
    }

    public static void toActivity(Activity activity, Class<?> clz, int id) {
        Intent intent = new Intent();
        intent.setClass(activity, clz);
        intent.putExtra("id", id);
        activity.startActivity(intent);
    }


    public static void toActivity(Activity activity, Class<?> clz, Intent intent) {
        intent.setClass(activity, clz);
        activity.startActivity(intent);
    }

    public static void toActivity(Activity activity, Class<?> clz, boolean sidIsZero) {
        Intent intent = new Intent();
        intent.setClass(activity, clz);
        intent.putExtra("sidIsZero", sidIsZero);
        activity.startActivity(intent);
    }

    public static void photoPreview(Activity activity, List<String> imgs, int index) {
        ImagePreview.getInstance()
                // 上下文，必须是activity，不需要担心内存泄漏，本框架已经处理好
                .setContext(activity)
                // 从第几张图片开始，索引从0开始哦~
                .setIndex(index)

                //=================================================================================================
                // 有三种设置数据集合的方式，根据自己的需求进行三选一：
                // 1：第一步生成的imageInfo List
                //  .setImageInfoList(imgs)

                // 2：直接传url List
                .setImageList(imgs)

                // 3：只有一张图片的情况，可以直接传入这张图片的url
                //.setImage(String image)
                //=================================================================================================

                // 加载策略，默认为手动模式
                .setLoadStrategy(ImagePreview.LoadStrategy.Default)

                // 保存的文件夹名称，会在SD卡根目录进行文件夹的新建。
                // (你也可设置嵌套模式，比如："BigImageView/Download"，会在SD卡根目录新建BigImageView文件夹，并在BigImageView文件夹中新建Download文件夹)
                .setFolderName("BigImageView/Download")

                // 缩放动画时长，单位ms
                .setZoomTransitionDuration(300)

                // 是否启用点击图片关闭。默认启用
                .setEnableClickClose(true)
                // 是否启用上拉/下拉关闭。默认不启用
                .setEnableDragClose(true)

                // 是否显示关闭页面按钮，在页面左下角。默认不显示
                .setShowCloseButton(false)
                // 设置关闭按钮图片资源，可不填，默认为库中自带：R.drawable.ic_action_close
                .setCloseIconResId(R.drawable.ic_action_close)

                // 是否显示下载按钮，在页面右下角。默认显示
                .setShowDownButton(true)
                // 设置下载按钮图片资源，可不填，默认为库中自带：R.drawable.icon_download_new
                .setDownIconResId(R.drawable.icon_download_new)

                // 设置是否显示顶部的指示器（1/9）默认显示
                .setShowIndicator(true)

                // 设置失败时的占位图，默认为库中自带R.drawable.load_failed，设置为 0 时不显示
                .setErrorPlaceHolder(R.drawable.load_failed)

                // 点击回调
                .setBigImageClickListener((view, position) -> {

                })
                // 长按回调
                .setBigImageLongClickListener((view, position) -> false)
                // 页面切换回调
                .setBigImagePageChangeListener(new OnBigImagePageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {

                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                })

                //=================================================================================================
                // 设置查看原图时的百分比样式：库中带有一个样式：ImagePreview.PROGRESS_THEME_CIRCLE_TEXT，使用如下：
                .setProgressLayoutId(ImagePreview.PROGRESS_THEME_CIRCLE_TEXT, new OnOriginProgressListener() {
                    @Override
                    public void progress(View parentView, int progress) {

                        // 需要找到进度控件并设置百分比，回调中的parentView即传入的布局的根View，可通过parentView找到控件：
                        ProgressBar progressBar = parentView.findViewById(R.id.sh_progress_view);
                        TextView textView = parentView.findViewById(R.id.sh_progress_text);
                        progressBar.setProgress(progress);
                        String progressText = progress + "%";
                        textView.setText(progressText);
                    }

                    @Override
                    public void finish(View parentView) {
                    }
                })


                .start();
    }

    public static boolean toUnLogin(Activity activity) {
//        if (((MyApplication)activity.getApplication()).getUser()==null){
//            ((MyApplication)activity.getApplication()).setLastToLgoin(activity);
//            Intent intent = new Intent(activity, LoginActivity.class);
//            intent.putExtra("isFromMain", true);
//            activity.startActivity(intent);
//            return true;
//        }else {
        return false;
//        }
    }

    public static String getFormatPhone(String str) {
        return str.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }

    public static String getMD5Str(String str) throws NoSuchAlgorithmException,
            UnsupportedEncodingException {
        MessageDigest messageDigest = null;

        messageDigest = MessageDigest.getInstance("MD5");

        messageDigest.reset();

        messageDigest.update(str.getBytes("UTF-8"));

        byte[] byteArray = messageDigest.digest();

        StringBuffer md5StrBuff = new StringBuffer();

        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(
                        Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }

        return md5StrBuff.toString();
    }

    //在这里抽取了一个方法   可以封装到自己的工具类中...
    public static String getFile(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        File file = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
        try {
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            InputStream is = new ByteArrayInputStream(baos.toByteArray());
            int x = 0;
            byte[] b = new byte[1024 * 100];
            while ((x = is.read(b)) != -1) {
                fos.write(b, 0, x);
            }
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Environment.getExternalStorageDirectory() + "/temp.jpg";
    }

    public static Bitmap btmap;

    public static Bitmap returnBitMap(final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;
                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    btmap = BitmapFactory.decodeStream(is);
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return btmap;
    }

    public static String getStringPrice(float price) {
        String result = null;
        try {
            result = "¥" + (price / 100.00);
        } catch (Exception e) {
            result = "¥???";
        }
        return result;
    }

    public static String getStringPrice(String price) {
        String result = null;
        try {
            result = "¥" + (Double.parseDouble(price) / 100.00);
        } catch (Exception e) {
            result = "¥???";
        }
        return result;
    }

    public static String getDisCount(String price) {
        String result = null;
        try {
            result = (Integer.parseInt(price) / 100) + "折";
        } catch (Exception e) {
            result = "???";
        }
        return result;
    }

    public static float getDisCountFloat(String price) {
        float result = 1.0f;
        try {
            result = (Float.parseFloat(price) / 1000.00f);
        } catch (Exception e) {
            result = 1.0f;
        }
        return result;
    }

    public static String stringToUtf8(String str) {
//        String result = null;
//        try {
//            result = URLEncoder.encode(str, "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//            result=str;
//        }
        return str;
    }

    public static String utf8ToString(String str) {
//        String result = null;
//        try {
//            result = URLDecoder.decode(str, "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//            result=str;
//        }
        return str;
    }


    @SuppressLint("ClickableViewAccessibility")
    public static void whenScrollClearFocus(View view, final EditText editText) {

        if (view instanceof ListView) {
            ((ListView) view).setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    editText.clearFocus();
                    return false;
                }
            });

        } else if (view instanceof ScrollView) {
            ((ScrollView) view).setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    editText.clearFocus();
                    return false;
                }
            });
        } else if (view instanceof RecyclerView) {
            ((RecyclerView) view).addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    editText.clearFocus();
                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    editText.clearFocus();
                }

            });
        }

    }

    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo("com.meetba.baotuan", 0);
            versionName = packageInfo.versionName;
            if (TextUtils.isEmpty(versionName)) {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 根据时间戳来判断当前的时间是几天前,几分钟,刚刚
     *
     * @param long_time
     * @return
     */
    public static String getTimeStateNew(String long_time) {
        String long_by_13 = "1000000000000";
        String long_by_10 = "1000000000";
        if (Long.valueOf(long_time) / Long.valueOf(long_by_13) < 1) {
            if (Long.valueOf(long_time) / Long.valueOf(long_by_10) >= 1) {
                long_time = long_time + "000";
            }
        }
        Timestamp time = new Timestamp(Long.valueOf(long_time));
        Timestamp now = new Timestamp(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//    System.out.println("传递过来的时间:"+format.format(time));
//    System.out.println("现在的时间:"+format.format(now));
        long day_conver = 1000 * 60 * 60 * 24;
        long hour_conver = 1000 * 60 * 60;
        long min_conver = 1000 * 60;
        long time_conver = now.getTime() - time.getTime();
        long temp_conver;
//    System.out.println("天数:"+time_conver/day_conver);
        if ((time_conver / day_conver) < 3) {
            temp_conver = time_conver / day_conver;
            if (temp_conver <= 2 && temp_conver >= 1) {
                return temp_conver + "天前";
            } else {
                temp_conver = (time_conver / hour_conver);
                if (temp_conver >= 1) {
                    return temp_conver + "小时前";
                } else {
                    return "刚刚";
                }
            }
        } else {
            return format.format(time);
        }
    }

    public static String formatTime(long timeMillis) {
        long long_by_13 = 1000000000000l;
        long long_by_10 = 1000000000l;
        if (timeMillis / long_by_13 < 1) {
            if (timeMillis / long_by_10 >= 1) {
                timeMillis = timeMillis * 1000l;
            }
        }
        return format(new Date(timeMillis));
    }

    private static String format(Date date) {
        Calendar calendar = Calendar.getInstance();
        //当前年
        int currYear = calendar.get(Calendar.YEAR);
        //当前日
        int currDay = calendar.get(Calendar.DAY_OF_YEAR);
        //当前时
        int currHour = calendar.get(Calendar.HOUR_OF_DAY);
        //当前分
        int currMinute = calendar.get(Calendar.MINUTE);
        //当前秒
        int currSecond = calendar.get(Calendar.SECOND);

        calendar.setTime(date);
        int msgYear = calendar.get(Calendar.YEAR);
        //说明不是同一年
        if (currYear != msgYear) {
            return new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault()).format(date);
        }
        int msgDay = calendar.get(Calendar.DAY_OF_YEAR);
        //超过7天，直接显示xx月xx日
        if (currDay - msgDay > 7) {
            return new SimpleDateFormat("MM月dd日", Locale.getDefault()).format(date);
        }
        //不是当天
        if (currDay - msgDay > 0) {
            if (currDay - msgDay == 1) {
                return "昨天";
            } else {
                return currDay - msgDay + "天前";
            }
        }
        int msgHour = calendar.get(Calendar.HOUR_OF_DAY);
        int msgMinute = calendar.get(Calendar.MINUTE);
        //不是当前小时内
        if (currHour - msgHour > 0) {
            //如果当前分钟小，说明最后一个不满一小时
            if (currMinute < msgMinute) {
                if (currHour - msgHour == 1) {//当前只大一个小时值，说明不够一小时
                    return 60 - msgMinute + currMinute + "分钟前";
                } else {
                    return currHour - msgHour - 1 + "小时前";
                }
            }
            //如果当前分钟数大，够了一个周期
            return currHour - msgHour + "小时前";
        }
        int msgSecond = calendar.get(Calendar.SECOND);
        //不是当前分钟内
        if (currMinute - msgMinute > 0) {
            //如果当前秒数小，说明最后一个不满一分钟
            if (currSecond < msgSecond) {
                if (currMinute - msgMinute == 1) {//当前只大一个分钟值，说明不够一分钟
                    return "刚刚";
                } else {
                    return currMinute - msgMinute - 1 + "分钟前";
                }
            }
            //如果当前秒数大，够了一个周期
            return currMinute - msgMinute + "分钟前";
        }
        //x秒前
        return "刚刚";
    }


    public static String getLongTime(String long_time) {

        String long_by_13 = "1000000000000";
        String long_by_10 = "1000000000";
        if (Long.valueOf(long_time) / Long.valueOf(long_by_13) < 1) {
            if (Long.valueOf(long_time) / Long.valueOf(long_by_10) >= 1) {
                long_time = long_time + "000";
            }
        }

        return long_time;
    }

    public static String getTime(String long_time) {

        String long_by_13 = "1000000000000";
        String long_by_10 = "1000000000";
        if (Long.valueOf(long_time) / Long.valueOf(long_by_13) < 1) {
            if (Long.valueOf(long_time) / Long.valueOf(long_by_10) >= 1) {
                long_time = long_time + "000";
            }
        }

        return TimeUtils.millis2String(Long.parseLong(long_time), new SimpleDateFormat("yyyy年MM月dd日 "));
    }

    public static String getTimeFormat(String long_time, String format) {
        String long_by_13 = "1000000000000";
        String long_by_10 = "1000000000";
        if (Long.valueOf(long_time) / Long.valueOf(long_by_13) < 1) {
            if (Long.valueOf(long_time) / Long.valueOf(long_by_10) >= 1) {
                long_time = long_time + "000";
            }
        }
        return TimeUtils.millis2String(Long.parseLong(long_time), new SimpleDateFormat(format));
    }


    public static String covnDate(String dateTime) {
        DateFormat df2 = null;
        Date date1 = null;
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss");
            Date date = df.parse(dateTime);
            SimpleDateFormat df1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
            date1 = df1.parse(date.toString());
            df2 = new SimpleDateFormat("MM/dd");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return df2.format(date1);
    }


    //检查权限
    public static boolean selfPermissionGranted(Context context, String permission) {
        int targetSdkVersion = 0;
        boolean ret = false;
        try {
            final PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            targetSdkVersion = info.applicationInfo.targetSdkVersion;
            Log.d("Permission", "selfPermissionGranted targetSdkVersion=" + targetSdkVersion);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (targetSdkVersion >= Build.VERSION_CODES.M) {
                ret = context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
            } else {
                ret = PermissionChecker.checkSelfPermission(context, permission) == PermissionChecker.PERMISSION_GRANTED;
            }
        } else {
            return true;
        }
        Log.d("Permission", "selfPermissionGranted permission:" + permission + " grant:" + ret);
        return ret;
    }


    //view 转bitmap
    public static Bitmap getBitmapFromView(View v) {
        Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        v.draw(canvas);
        return bitmap;
    }

    public static Bitmap getNetBitmap(String urlpath) {
        Bitmap map = null;
        try {
            URL url = new URL(urlpath);
            URLConnection conn = url.openConnection();
            conn.connect();
            InputStream in;
            in = conn.getInputStream();
            map = BitmapFactory.decodeStream(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    private static long clickTime;

    //防止点击事件频繁触发
    public static boolean fastClick() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - clickTime > 700) {
            clickTime = currentTime;
            return true;
        } else {
            return false;
        }
    }


    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置信息栏颜色
     *
     * @param activity
     */
    public static void setTitleBarColor(Activity activity) {
        Window window = activity.getWindow();
        //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        //设置状态栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setStatusBarColor(activity.getResources().getColor(R.color.colorWhite));
        }
    }

    public static void setTitleBarColor(Activity activity, int corlor) {

        Window window = activity.getWindow();
        //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        //设置状态栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setStatusBarColor(activity.getResources().getColor(corlor));
        }
    }

    public static String phoneHidden(String phone) {
        return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }


    //将base64转换成Bitmap类型
    public static Bitmap stringtoBitmap(String string) {
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    /**
     * 根据自己的时间去定义一个Toast 输入时间为毫秒
     *
     * @param c
     * @param info
     * @param time
     */
    public static void setToatBytTime(Context c, String info, int time) {
        final Toast toast = Toast.makeText(c, info, Toast.LENGTH_SHORT);
        toast.show();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                toast.cancel();
            }
        }, time);
    }


    /**
     * 给textview 赋值
     *
     * @param s        字符串
     * @param textView 文本
     */

    public static void textviewSetText(String s, TextView textView) {
        if (s == null || s.equals("")) {
            textView.setText("---");
        } else {
            textView.setText(s);
        }
    }

    public static void textviewSetText(String title, String s, TextView textView) {
        if (s == null || s.equals("")) {
            textView.setText(title + "---");
        } else {
            textView.setText(title + s);
        }
    }


    /**
     * String 转 int
     *
     * @param str String
     * @return
     */
    public static int stringToInt(String str) {

        try {
            return Integer.parseInt(str);
        }catch (Exception e){
            return -1;
        }

    }

    public static Float stringToFloat(String str) {

        return Float.parseFloat(str);
    }


    //将Bitmap转换成base64字符串

    public static String listCastString(ArrayList<String> datas) {
        String s = "";
        for (String f : datas) {
            s = s + f + ",";
        }
        return s.substring(0, s.length() - 1);
    }

    public static String listCastString(List<String> datas) {
        String s = "";
        for (String f : datas) {
            s = s + f + ",";
        }
        return s.substring(0, s.length() - 1);
    }

    public static boolean isCotain(ArrayList<String> strings, String s) {
        boolean flag = false;
        for (String string : strings) {
            if (string.equals(s)) {
                flag = true;
            }
        }
        return flag;
    }

    public static boolean isCotain(ArrayList<String> a, ArrayList<String> b) {
        boolean flag = true;
        for (String s : b) {
            if (!a.contains(s)) {
                flag = false;
            }
        }
        return flag;
    }


    public static String getHtmlStringSingle(String info, String color) {

        return "<font color=\"" + color + "\">" + info + "</font>";
    }


}
